package cn.itsource.ymcc.config;

import cn.itsource.ymcc.domain.Login;
import cn.itsource.ymcc.domain.Permission;
import cn.itsource.ymcc.service.ILoginService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

@Component
public class UserDetailServiceImpl implements UserDetailsService {
    @Autowired
    private ILoginService loginService;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据 用户
        Login login = loginService.getOne(new QueryWrapper<Login>().eq("username", username));
        if(login == null){
            return null; //只要你这里返回null  直接登录失败
        }
        List<Permission> permissionList = loginService.selectSN(login.getId());
        //得到权限集合
//        List<GrantedAuthority> grantedAuthorities = strings.stream()
//                .map(SimpleGrantedAuthority::new).collect(Collectors.toList());
        //
//        List<GrantedAuthority> grantedAuthorities =
//                permissionList.stream()
//                        .map(Permission::getSn)
//                        .map(SimpleGrantedAuthority::new)
//                        .collect(Collectors.toList());

        List<GrantedAuthority> grantedAuthorities =
                permissionList.stream()
                        .map(permission ->  new SimpleGrantedAuthority(permission.getSn()))
                        .collect(Collectors.toList());



        return new User(JSON.toJSONString(login),login.getPassword(),grantedAuthorities);
    }
}
